package servlet;

import controller.UserController;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import manager.FileManager;
import manager.LogManager;

/**
 * DownloadServlet
 *
 * Handle file downloads. Uses FileManager to get the appropriate blob and
 * outputs this. Also has access restriction and logging functionality.
 */
public class DownloadServlet extends HttpServlet {

    @EJB
    private FileManager fileManager;
    @EJB
    private LogManager logManager;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UserController userController = (UserController) request.getSession().getAttribute("userController");
        Integer id = null;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (Exception e) {
        }

        ServletOutputStream sos = response.getOutputStream();
        try {
            if (userController != null && userController.isLoggedIn()) {
                if (id != null) {
                    //response.setContentType("image/jpg");
                    try {
                        byte[] data = fileManager.getFileBlob(id);
                        logManager.logDownload(userController.getUser().getId(), id);
                        sos.write(data);
                    } catch (Exception e) {
                        logManager.logError("download", "User "
                                + userController.getUser().getUsername()
                                + " tried to download file id " + id
                                + " which does not exist");
                        response.sendRedirect("/filecityee/");
                    }
                } else {
                    logManager.logError("download", "User "
                            + userController.getUser().getUsername()
                            + " accessed download without an id");
                    response.sendRedirect("/no_id");
                }
            } else {
                String ip = request.getRemoteAddr();
                logManager.logWarning("download", "Download page was accessed by unauthorized user from ip " + ip);
                response.sendRedirect("/not_loggedin");
            }
        } finally {
            sos.close();
        }
    }
}
